/*
 * @Description: 弹窗表格
 * @Author: Zzt
 * @Date: 2022-12-31 11:44:30
 * @LastEditTime: 2023-02-01 09:31:50
 */
import { uploadPath } from '@/api/upload';
import { Button, Space, Table, Upload } from 'antd';
import { ColumnsType } from 'antd/lib/table';
import { UploadChangeParam, UploadFile } from 'antd/lib/upload';
import classNames from 'classnames/bind';
import { useEffect, useMemo, useState } from 'react';
import { useBusinessGuidanceContext } from '../../contexts/BusinessGuidanceContext';
import styles from '../../styles/guidance.module.scss';
import { byteConvert } from '@/utils';

const cx = classNames.bind(styles);
const TabelList = (props: any) => {
  const { SaveAnnex, DelectAnnual, enclosureList } = useBusinessGuidanceContext();
  const [no, setNo] = useState(enclosureList.length + 1);
  const columns: ColumnsType = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'fileNo',
      key: 'fileNo'
    },
    {
      title: '附件名称',
      dataIndex: 'fileName',
      align: 'center',
      key: 'fileName',
      width: '30%'
    },
    {
      title: '格式',
      dataIndex: 'fileExt',
      align: 'center',
      key: 'fileExt'
    },
    {
      title: '附件大小',
      dataIndex: 'fileSize',
      align: 'center',
      key: 'fileSize',
      render: (size: number) => byteConvert(size)
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (_, record: any, index) => (
        <Space size="small">
          <Button size="small" type="link" href={record.fileUrl} target={'_blank'} download>
            下载
          </Button>
          <Button size="small" type="link" href={record.fileUrl} target={'_blank'}>
            浏览
          </Button>
          <Button size="small" type="link" danger onClick={() => DelectAnnual(record.fileNo)}>
            删除
          </Button>
        </Space>
      )
    }
  ];

  const onChange = (info: UploadChangeParam<UploadFile>) => {
    const { file } = info;

    if (file.status === 'done') {
      saveExcel(file, file.response);
    }
  };

  const saveExcel = (file: UploadFile, res: any) => {
    const annex = {
      fileNo: no,
      fileName: file.name,
      fileSize: file.size,
      fileUrl: res.data?.url || '',
      fileExt: res.data?.ext || '',
      filePath: res.data?.path || ''
    };
    setNo((state: any) => state + 1);
    SaveAnnex(annex);
  };

  return (
    <>
      <div className={cx('dash')}>
        附件管理
        <Upload
          action={uploadPath}
          name="file"
          maxCount={1}
          onChange={onChange}
          showUploadList={false}
        >
          <Button type="link">+添加附件</Button>
        </Upload>
      </div>
      {useMemo(
        () => (
          <Table
            columns={columns}
            dataSource={enclosureList}
            size="small"
            rowKey={'fileNo'}
          ></Table>
        ),
        [enclosureList]
      )}
    </>
  );
};
export default TabelList;
